package NetWork.Exercise002;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName:Server
 * Package:NetWork.Exercise001
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/3/7-22:41
 * @Version:v1.0
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //创建对象绑定1000端口
        ServerSocket serverSocket = new ServerSocket(1000);
        //等待客户端连接
        System.out.println("---等待客户端连接---");
        Socket socket =serverSocket.accept();
        System.out.println("---已经有客户端连接---");

        //读取数据
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        int b;

        /*细节：
        * read方法会从连接通道中读取数据
        * 但是,需要有一个结束标记,此处的循环才会停止
        * 否则,程序就会一直停在read方法这里,等待读取下面的数据*/
        while ((b=br.read())!=-1){

            System.out.print((char) b);
        }
        System.out.println();
        System.out.println("-----数据读取完毕准备回写----");
        //回写数据
        String str= "接收成功";
        OutputStream os = socket.getOutputStream();
        os.write(str.getBytes());

        System.out.println("回写成功");
        //释放资源
        br.close();
        socket.close();
    }
}
